package com.hassean.we.admin.common.Interceptor;

import com.alibaba.fastjson.JSON;
import com.hassean.we.admin.common.constant.CommonConstant;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
     * 权限拦截器
     *
     * @author   yajun
     * @create    2019年4月25日
     */
    public class AuthInterceptor implements HandlerInterceptor {

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
            //System.out.println(">>>AuthInterceptor>>>>>>>在请求处理之前进行调用（Controller方法调用之前）");
            String  token =   request.getParameter("token");
            boolean flag = false;
            //flag = passAuth(token);//权限验证
            flag = true;//测试打开
            System.out.println("flag:"+flag);
            if(flag) {
                System.out.println("我权限通过");
                return true;// 只有返回true才会继续向下执行，返回false取消当前请求
            }else {
                System.out.println("我被拦截");
                return false; //如果false，停止流程，api被拦截
            }



        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                               ModelAndView modelAndView) throws Exception {
            //System.out.println(">>>AuthInterceptor>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
                throws Exception {
            //System.out.println(">>>AuthInterceptor>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
        }

    //权限验证
    public boolean passAuth(String token) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(CommonConstant.passAuthUrl+"/auth/oauth/check_token");
        List<NameValuePair> params=new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("token",token));
        //添加参数
        try {
            post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            HttpResponse response =  client.execute(post);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "utf-8");
            System.out.println(result);


            Map<String ,Object> map = JSON.parseObject(result, Map.class);
            //System.out.println(" map.get(\"username\"):"+ map.get("user_name"));
            if( result.contains("user_name")){
                return true;//认证通过
            } else {
                return false;//认证没有通过
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return  false;
    }
}
